import axios from 'axios'
import ImagesList from './ImagesList'
import { useState, useEffect, useRef, useCallback } from 'react'
import api from '../servers/api'
import { CircularProgress } from '@material-ui/core'
import { makeStyles } from '@material-ui/core/styles'
import InfiniteScroll from 'react-infinite-scroll-component'

function New() {
    const useStyles = makeStyles({
        root: {
            position: 'fixed',
            left: '0',
            right: '0',
            top: '0',
            bottom: '0',
            display: 'flex',
            justifyContent: 'center',
            alignItems: 'center',
        }
    })
    const rootStyle = useStyles().root
    const images = useRef([])
    const [start, setStart] = useState('')
    const next = useRef('')
    const hasNext = useRef(false)
    const [isLoading, setLoadingStatus] = useState(true)
    const [renderJsx, setRenderJsx] = useState(<div className={rootStyle}>
        <CircularProgress />
    </div>)
    useEffect(() => {
        async function getImages() {
            setLoadingStatus(true)
            const { data } = await axios.get(api.bqz.new, {
                params: {
                    start
                }
            })
            let imagesResult = data.data.objectList
            imagesResult = imagesResult.filter(Boolean).map(image => {
                image.url = image.smallURL.replace(/\d{3}x/, (result) => {
                    return parseInt(result) > 240 ? '240x' : result
                })
                return image
            })
            next.current = data.data.nextStart
            hasNext.current = data.data.more
            images.current = images.current.concat(imagesResult)
            setLoadingStatus(false)
        }
        getImages()
    }, [start]);
    const loadNext = useCallback(() => {
        setStart(next.current)
    }, [])
    useEffect(() => {
        if (!isLoading) {
            setRenderJsx((
                <InfiniteScroll next={loadNext} dataLength={images.current.length} hasMore={hasNext}>
                    <ImagesList images={images.current} />
                </InfiniteScroll>
            ))
        }
    }, [isLoading, images, hasNext, loadNext])
    return renderJsx
}

export default New